package 
{
	import flash.display.*;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	[SWF( backgroundColor = '0x000000', frameRate = '100', width = '800', height = '600')]
	
	public class Main extends Sprite 
	{
		//private var menu:SIF;
		private var mb:Mandelbrot; 
		private var zoombox:Sprite = new Sprite();
		private var autoZoom:int = -1;
		private var cycle:Boolean = false;
		private var timer:Timer = new Timer(400);
		public function Main():void 
		{
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		private function init(e:Event = null):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
			mb = new Mandelbrot(stage.stageWidth, stage.stageHeight);			
			addChild(mb);
			addChild(zoombox);
			stage.addEventListener(KeyboardEvent.KEY_DOWN, handleKeys);
			addEventListener(MouseEvent.CLICK, mb.zoomIn);
			addEventListener(MouseEvent.MOUSE_MOVE, moveZoombox);
			timer.addEventListener(TimerEvent.TIMER, step);
			timer.start();
		}
		private function moveZoombox(e:MouseEvent):void
		{
			drawZoombox(e.localX, e.localY);
		}
		private function drawZoombox(x:int,y:int):void
		{
			zoombox.graphics.clear();
			zoombox.graphics.lineStyle(2, 0xffffff);
			zoombox.graphics.drawRect(x - (mb.rb.width * 0.5 * mb.zoomFactor), y - (mb.rb.height * 0.5 * mb.zoomFactor), mb.rb.width * mb.zoomFactor, mb.rb.height * mb.zoomFactor);									
					
		}
		public function handleKeys(e:KeyboardEvent):void
		{
			//on 'space' reset the view and make a new set
			if (e.keyCode==32)
			{
				removeChild(mb);
				removeChild(zoombox);
				removeEventListener(MouseEvent.CLICK, mb.zoomIn);
				mb = new Mandelbrot(mb.rb.width, mb.rb.height);
				addChild(mb);
				addChild(zoombox);
				addEventListener(MouseEvent.CLICK, mb.zoomIn);
			}			
			//on 'up' or 'down' change size of zoombox
			if(e.keyCode==38)
				mb.zoomFactor *= 0.9;
			if(e.keyCode==40)
				mb.zoomFactor *= 1.11;
			//on 'c' toggle color cycling
			if (e.keyCode == 67)
			{
				cycle = !cycle;
			}
			//on 'f' toggle full screen
			if (e.keyCode == 70)
			{
				stage.displayState = (stage.displayState == StageDisplayState.FULL_SCREEN)?StageDisplayState.NORMAL:StageDisplayState.FULL_SCREEN;
			}
			//on 'enter' toggle auto zoom
			if (e.keyCode == 13)			
			{
				
				if (autoZoom == -1)
				{
					autoZoom = 0;
				}
				else if (autoZoom == 0)
				{
					autoZoom = 1;
				}
				else if (autoZoom == 1)
				{
					autoZoom = -1;
				}
				
			}
			drawZoombox(mouseX,mouseY);
		}
		private function step(e:TimerEvent):void
		{
			if(cycle)
				mb.cycle(0);
			if(autoZoom==0)
				mb.zoom(0.9);
			if (autoZoom == 1)
				mb.zoom(1.1);
			if (autoZoom == -1)
				mb.zoomFactor = 0.5;
		}
		
		
	}
	
}